﻿
#include "thread.h"
#include "common.h"
//---------------------------------------------------------------------------

TThread::TThread() : Working(false), FreeOnTerminate(false),
	ThreadID(0), ExitCode(0), Active(0)
{
	pthread_attr_t attr;								//设置线程分离属性
	pthread_attr_init(&attr);
	if (0 == pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED))
		pthread_create(&ThreadID, &attr, ThdProc, this);
}
//---------------------------------------------------------------------------

TThread::~TThread()
{
	Working = false;
	//pthread_cancel(ThreadID);
}
//---------------------------------------------------------------------------

void TThread::Stop()
{
	Working = false;
}
//---------------------------------------------------------------------------

void * TThread::ThdProc(void * lpParameter)
{
	TThread *thd = (TThread*)lpParameter;
	if (thd)
	{
		thd->Active = 1;
		while (!thd->Working)
		{
			SleepEx(10, NULL);
		}

		thd->Execute();
		if (thd->FreeOnTerminate)
		{	//如果为自释放则自动删除该线程
			delete thd;
			return NULL;
		}
		return (void *)(thd->ExitCode);
	}

	return NULL;
}
//---------------------------------------------------------------------------

